<template>
    <ul v-if="brandList.length" class="brand-preview">
        <li v-for="item in brandList" :key="item.type">
            <UxPopper>
                <img v-if="item.type == 'pack'" src="@/assets/images/brands/brands-packaging.png" alt="">
                <img v-if="item.type == 'tag'" src="@/assets/images/brands/brands-hangtag.png" alt="">
                <strong v-text="getTemplateName(item)"></strong>
                <div class="brand-preview-popper" slot="pop">
                    <figure v-for="model in item.previews" :key="model.canvas_name" :loading="model.loading">
                        <img v-for="img in model.image" :key="img.url" :src="img.url" :style="img.style" @load="onStatechange(img,$event)" @error="onStatechange(img,$event)">
                        <span v-text="$getSurfaceNameFormat(model.surface_name)"></span>
                    </figure>
                </div>
            </UxPopper>
            <!-- <CommonCurrencyRate :price="item.total_price" :cover="currencyCover" :other="{pre:'-'}" type="pre|unit|price" /> -->
            <CommonLevelDiscount :price="item.total_price" :level="userInfo.level" :other="{pre:'-'}" :type="discount || 'pre|unit|discount|icon'" />

        </li>
    </ul>
</template>
<script>
import { mapGetters, mapState } from "vuex";

export default {
    name: "BrandPreview",
    props: {
        tag: { type: Object, default: null },
        pack: { type: Object, default: null },
        currencyCover: { type: Object, default: null },
        discount: { type: String, default: '' },
    },
    data () {
        return {
            brandList: [],
        };
    },
    computed: {
        ...mapGetters("user", {
            userInfo: "getUserInfo",
        }),
    },

    watch: {
        tag () {
            this.getBrandList();
        },
        pack () {
            this.getBrandList();
        },
    },
    methods: {
        getBrandList () {
            const result = []
            this.pack && result.push({ ...this.pack, type: 'pack' });
            this.tag && result.push({ ...this.tag, type: 'tag' });
            this.brandList = result.map(item => {
                try {
                    const design = item.design_list || item.design;
                    const model = item.tag_model || item.pack_model || item.model_img || item.model;

                    item.design = Array.isArray(design) ? design : JSON.parse(design || '[]');
                    item.model_img = Array.isArray(model) ? model : JSON.parse(model || '[]');

                } catch (error) {
                    console.log(error)
                }

                const piecesObject = Object.fromEntries(item.design.map((i) => [i.surface_name, i]));
                const models = item.model_img.filter(model => {
                    const used = model.mapping.filter(m => {
                        const piece = piecesObject[m.canvas_name] || { layers: [] }
                        const layers = typeof piece.layers == 'string' ? JSON.parse(piece.layers) : piece.layers;
                        return layers.length > 0 && piece.output_img
                    })
                    return used.length > 0
                });

                item.loading = true;
                item.previews = models.map(model => {
                    const preview = {
                        canvas_name: model.canvas_name,
                        surface_name: model.surface_name,
                        loading: true,
                        image: []
                    }
                    // 背景图
                    model.mask_image && preview.image.push({
                        url: this.$getImageUrl(model.mask_image),
                        style: null,
                    });

                    // 渲染图
                    model.mapping.map(mapper => {
                        const piece = piecesObject[mapper.canvas_name] || { layers: [] }
                        const layers = typeof piece.layers == 'string' ? JSON.parse(piece.layers) : piece.layers;

                        layers.length > 0 && piece.output_img && preview.image.push({
                            url: this.$getLitimgUrl(piece.output_img),
                            name: mapper.canvas_name,
                            style: {
                                left: 100 * (mapper.x / model.outer_width) + '%',
                                top: 100 * (mapper.y / model.outer_height) + '%',
                                width: 100 * (mapper.width / model.outer_width) + '%',
                                height: 100 * (mapper.height / model.outer_height) + '%',
                            }
                        });
                    })
                    return preview
                })

                return item;
            })

            this.onStatechange();
        },

        getTemplateName (obj) {
            return obj.tag_name || obj.pack_name || obj.template_name
        },


        onStatechange (img, event) {
            if (this.$el) {
                const poppers = this.$el.querySelectorAll('.brand-preview-popper');
                Array.prototype.slice.call(poppers).map((elem, index) => {
                    const images = Array.prototype.slice.call(elem.querySelectorAll('img'));
                    const unload = images.filter(img => !img.complete);
                    const item = this.brandList[index];
                    item && (item.loading = unload.length > 0);
                })
            } else {
            }
        }

    },
    created () {
        this.getBrandList();
    }
};
</script>
<style lang="scss" scoped>
.brand-preview {
    box-sizing: border-box;
    display: flex;
    justify-content: center;
    background: rgba(250, 241, 212, 0.5);
    height: 40px;

    & > li {
        display: flex;
        justify-content: center;
        box-sizing: border-box;
        overflow: hidden;
        white-space: nowrap;
        text-overflow: ellipsis;
        align-items: center;
        line-height: 20px;
        color: #000;

        & + li {
            margin-left: 8px;
        }

        &::v-deep .popper-name {
            display: flex;
            align-items: center;
            border-radius: 8px;
            padding: 0 4px;
            height: 28px;
            color: #000000;

            strong {
                display: block;
                font-weight: normal;
                font-family: Roboto-Regular, Roboto;
                font-weight: 400;
                font-size: 14px;
                line-height: 16px;
                overflow: hidden;
                text-overflow: ellipsis;
                white-space: nowrap;
                max-width: 90px;
            }

            & > img {
                width: 20px;
                height: 20px;
                border-radius: 20px;
                margin-right: 4px;
            }

            &:hover {
                text-decoration: none;
                color: #ea4c89;
                background: #ede6d5;
            }
        }

        & > .level-discount {
            font-size: 14px;
            padding-right: 4px;
            &::v-deep span[name='pre'] {
                width: 4px;
                text-align: center;
                color: #000;
            }
        }
    }

    .brand-preview-popper {
        display: flex;
        position: relative;
        box-sizing: border-box;
        padding: 4px;

        &[loading] {
            &::after {
                content: '';
                position: absolute;
                left: 0;
                top: 0;
                right: 0;
                bottom: 0;
                background-image: url(@/assets/images/loading.gif);
                background-position: center;
                background-size: 32px 32px;
                background-repeat: no-repeat;
            }
            figure {
                opacity: 0;
            }
        }

        figure {
            width: 240px;
            height: 240px;
            margin: 24px 4px 4px;
            position: relative;
            background: #f6f6f6;

            img {
                position: absolute;
                left: 0;
                top: 0;
                width: 100%;
                height: 100%;
            }

            & > span {
                position: absolute;
                left: 0;
                right: 0;
                top: -22px;
                text-align: center;
                font-size: 14px;
                font-family: Roboto-Regular, Roboto;
                font-weight: 400;
                color: #212121;
                line-height: 16px;
            }
        }
    }
}
</style>
